<?php
namespace app\home\controller;
use think\Db;
class Goods extends Base{
 	public function _initialize(){
        parent::_initialize();
        $where['id'] = array('neq',1);
        $gc=M("Goods_category")->where($where)->order("sort asc")->select();
        $this->assign("gc",$gc);
    }
	//空操作
	public function _empty(){
		header("HTTP/1.0 404 Not Found");
		$this->display('Public:404');
	}
	
	/**
	*首页
	*/
	public function index(){
		//幻灯
		$f=M("App_flash")->limit(6)->select();
		$this->assign("f",$f);
		$Goods = M('Goods'); // 实例化User对象
		$where['goods_category'] = array('neq',1);
		$where['status'] = 1;
		$list = $Goods->where($where)->order('add_time desc')->paginate(20,false,['query'=>input()]);
		$page = $list->render();
		$this->assign('list',$list);// 赋值数据集
		$this->assign('page',$page);//分页
		return $this->fetch();
	}

	/**
	*详情页面
	*/
	public function details(){
		$id=I("id","");
		if(empty($id)){
			$this->error("无效参数");
		}
		$list=M("Goods")->where(['id'=>$id,'status'=>1])->find();
		$res = db('Goods_category')->where(['id'=>$list['goods_category']])->find();
		$this->assign('category',$res['name']);
		if(empty($list)){
			$this->error("无效数据");
		}
		$this->assign("list",$list);
		return $this->fetch();
	}
	/**
	*商品列表页面
	*/
	public function goods_list(){
		$id=I("id");
		$gc=M("Goods_category")->where(array('id'=>$id))->find();
		$this->assign("category",$gc['name']);
		if(!empty($id)){
			$where['goods_category']=$id;
		}
		$name=input("name");
		if(!empty($name)){
			$where['name']=array("like",'%'.$name.'%');
		}
		$where['status']=1;
		$Goods = M('Goods'); // 实例化User对象
		$list = $Goods->where($where)->order('add_time desc')->paginate(10,false,['query'=>input()]);
		$page = $list->render();
    	$this->assign('page',$page);//分页
    	$this->assign('list',$list);// 赋值数据集
		return $this->fetch();
	}

	/**
	*购物车 
	*/
	public function cart(){
		

		$Buy_cart = M('Buy_cart'); // 实例化User对象
		$where['member_id']=$_SESSION['think']['USER_KEY_ID'];
		$where['status']=1;
		$list = $Buy_cart->where($where)->order('add_time desc')->paginate(15,false,['query'=>input()]);
		$money="";
		$all_money="";
		$page = $list->render();
		$list = $list->all();
		foreach ($list as $k=>$v){
				$goods=M("Goods")->where(['id'=>$v['goods_id']])->find();
				$list[$k]['all_money']=empty($goods['all_money'])?0:$goods['all_money'];
				$list[$k]['money']=empty($goods['money'])?0:$goods['money'];
				$list[$k]['pic']=$goods['pic'];
				$list[$k]['name']=$goods['name'];
				$money+=($v['num']*$goods['money']);
				$all_money+=($v['num']*$goods['all_money']);
		}
		$this->assign("money",$money);
		$this->assign("all_money",$all_money);
    	$this->assign('page',$page);//分页
    	$this->assign('list',$list);// 赋值数据集
		return $this->fetch();
	}
	/**
	 * 加入购物车
	 */
	public function add_cart(){
		$id=I('id',"");
		if(empty($id)){
			$msg['status']=-2;
			$msg['info']="商品序列错误，请联系管理员";
			return json($msg);exit;
		}
		$num=I('num',"");
		if(empty($num) || !is_numeric($num) || $num<=0 ){
			$msg['status']=-3;
			$msg['info']="请输入正确数量";
			return json($msg);exit;
		}
		$bc=M("Buy_cart")->where(['goods_id'=>$id,'status'=>1,'member_id'=>$_SESSION['think']['USER_KEY_ID']])->find();
		if(!empty($bc)){
			$msg['status']=-5;
			$msg['info']="该商品已经存在购物车";
			return json($msg);exit;
		}
		
		
		$goods=M("Goods")->where(['id'=>$id,'status'=>1])->find();
		if(empty($goods)){
			$msg['status']=-1;
			$msg['info']="无效数据";
			return json($msg);exit;
		}
		
		$data=array(
			'goods_id'=>$id,
			'member_id'=>$_SESSION['think']['USER_KEY_ID'],
			'num'=>$num,
			'add_time'=>time(),
			'status'=>1,
		);
		$re=M('Buy_cart')->add($data);
		if($re){
			$msg['status']=1;
			$msg['info']="购物车添加成功";
			return json($msg);exit;
		}else {
			$msg['status']=2;
			$msg['info']="购物车添加失败";
			return json($msg);exit;
		}
	}
	/**
	 *删除购物车方法
	 */
	public function del_cart(){
		$id=I("id","");
		if(empty($id)){
			$msg['status']=-1;
			$msg['info']="无效参数";
			return json($msg);exit();
		}
		$bc=M("Buy_cart")->where(['id'=>$id,'member_id'=>$_SESSION['think']['USER_KEY_ID']])->find();
		if(empty($bc)){
			$msg['status']=-2;
			$msg['info']="无效数据";
			return json($msg);exit();
		}
		$re=M("Buy_cart")->where(['id'=>$id,'member_id'=>$_SESSION['think']['USER_KEY_ID']])->delete();
		if($re){
			$msg['status']=1;
			$msg['info']="删除成功";
			return json($msg);exit();
		}else{
			$msg['status']=-3;
			$msg['info']="删除失败";
			return json($msg);exit();
		}
	}

	/**
	 * 购物车结算方法
	 */
	public function cart_settlement(){
		$name=input('name');//收货人
		$phone=input("phone","");//收货人电话
		$address=input("address","");//收货地址
		$sheng_id = input('sheng');
		$sh = M('Areas')->where("areaId='{$sheng_id}'")->find();
		$sheng = $sh['areaName'];
		$s = M('Areas')->find(I('shi'));
		
		$shi = $s['areaName'];
		$q = M('Areas')->find(I('qu'));
		$qu = $q['areaName'];

		$dizhi=$sheng.$shi.$qu;//省市联动
		$xiaofei=input('xiaofei');//消费金额 只为做对比
		
		
		$buycart=$this->cart_money();
		if($buycart['status']!=1){
			$msg['status']=-1;
			$msg['info']=$buycart['info'];
			return json($msg);exit;
		}
		

		$list = $buycart['bc'];
// 		$goods_id=I('gid',"");//商品id
		$account_type = input('account_type');
		$money=$buycart['info'];
		//先付款 在提交订单
		//获取当前用户的重复币的余额
		$yue = $this->balance($_SESSION['think']['USER_KEY_ID'],2);
		if($yue<$money){
			$msg['status']=-2;
			$msg['info']="您的余额不足，无法购买";
			return json($msg);exit;
		}
		Db::startTrans(); //启动事务
		$re[]=M('App_member_account')->where(array('member_id'=>$_SESSION['think']['USER_KEY_ID']))->setDec("account_type_2",$money);
		foreach ($list as $k=>$v){
			$re[]=$this->add_goods_user($v['goods_id'], $v['id'], $v['num'], $v['money'],$name,$phone,$dizhi,$address);//添加订单日志
			$re[]=M("Buy_cart")->where(['id'=>$v['id']])->setField("status",2);//购物车设置已经购买
			$re[]=M("Goods")->where(['id'=>$v['goods_id']])->setDec("shengyu_num",$v['num']);//减少库存
		}
	
		
		if(!in_array(false,$re)){
			Db::commit();
			$msg['status']=1;
			$msg['info']="付款成功";
			return json($msg);exit;
		}else{
			Db::rollback();
			$msg['status']=-4;
			$msg['info']="付款失败";
			return json($msg);exit;
		}
		
	}
	
	/**
	 * 添加订单表方法(付完款才会添加订单表)
	 */
	public function add_goods_user($goodsid,$bcid,$num,$money,$name,$phone,$dizhi,$address){
		$data['goods_id']=$goodsid;
		$data['bc_id']=$bcid;
		$data['num']=$num;
		$data['money']=$money;
		$data['member_id']=$_SESSION['think']['USER_KEY_ID'];
		$data['add_time']=time();
		$data['status']=1;
		$data['order_num']="SK".time().rand(1000, 9999);
		$data['s_name']=$name;
		$data['phone']=$phone;
		$data['dizhi']=$dizhi;
		$data['address']=$address;
		$data['status']=0;
		$re=M("Goods_user")->add($data);
		if($re){
			return true;
		}else{
			return false;
		}
	}
	
	public function lig_settlement(){
		$name=input('name');//收货人
		$phone=input("phone");//收货人电话
		$address=input("address");//收货地址
		$sheng_id = input('sheng');
		$sh = M('Areas')->where("areaId='{$sheng_id}'")->find();
		$sheng = $sh['areaName'];
		$s = M('Areas')->find(I('shi'));
		
		$shi = $s['areaName'];
		$q = M('Areas')->find(I('qu'));
		$qu = $q['areaName'];

		$dizhi=$sheng.$shi.$qu;//省市联动
		$xiaofei=input('xiaofei');//消费金额 只为做对比\
		$goods_id=input('gid');//商品id 
		$num=input('num');//获取购买数量 	
		$good =M('Goods')->where(array('id'=>$goods_id))->find();
		$yue = $this->balance($_SESSION['think']['USER_KEY_ID'],2);
		$goods_money = $good['money'];
		if($yue<$goods_money){
			$msg['status']=-2;
			$msg['info']="您的余额不足，无法购买";
			return json($msg);exit;
		}
		Db::startTrans(); //启动事务
		$re[]=M('App_member_account')->where(array('member_id'=>$_SESSION['think']['USER_KEY_ID']))->setDec("account_type_2",$goods_money);
		$re[]=$this->add_goods_user($goods_id,0,$num,$goods_money,$name,$phone,$dizhi,$address);
		$re[]=M("Goods")->where(['id'=>$goods_id])->setDec("shengyu_num",(int)$num);//减少库存
		if(!in_array(false,$re)){
			Db::commit();
			$msg['status']=1;
			$msg['info']="付款成功";
			return json($msg);exit;
		}else{
			Db::rollback();
			$msg['status']=-4;
			$msg['info']="付款失败";
			return json($msg);exit;
		}
	}
	/**
	 * 立即购买结算放方法
	 * 
	 */
	public function lig(){
		if(IS_POST){
			$parent_id['parentId'] = I('post.pro_id','addslashes');
			$region = M('Areas')->where($parent_id)->select();
			$opt = '<option>--请选择市区--</option>';
			foreach($region as $key=>$val){
				$opt .= "<option value='{$val['areaId']}'>{$val['areaName']}</option>";
			}
			//dump($opt);die();
			echo $opt;
		}else{
			// 获取购买商品的id
			$parent_id['parentId'] = 0;
			$region = M('Areas')->where($parent_id)->select();
			$this->assign('region',$region);
			$gid = I('id');
			//获取购买的数量
			$num = I('num');
			//获取购买商品的单价
			$res = M('Goods')->where(array('id'=>$gid))->find();
			//dump(I());die;
			if($res['shengyu_num']<$num){
				$this->error($res['name']."库存不足".$res['num']."只有".$res['shengyu_num']);
			}
			$price = $res['money'];//商品的会员价格
			$allmoney = $num*$price;//商品的总价格
			$where['member_id'] = $_SESSION['think']['USER_KEY_ID']; 
			$where['status'] = 1;
			$address = M('App_address')->where($where)->find();
			$sheng = M('Areas')->where("areaId='{$address['province_id']}'")->find();
			$address['province'] = $sheng['areaName'];
			$shi = M('Areas')->where("areaId='{$address['city_id']}'")->find();
			$address['city'] = $shi['areaName'];

			$qu = M('Areas')->where("areaId='{$address['area_id']}'")->find();
			$address['area'] = $qu['areaName'];
			//dump($address);die;
			$this->assign("allmoney",$allmoney);
			$this->assign("address",$address);
			$this->assign("gid",$gid);
			$this->assign("num",$num);
		}

		
		return $this->fetch();
	
	} 
	
	/**
	*收货地址页面 
	*/
	public function address_add(){
		$parent_id['parentId'] = 1;
		$region = M('Areas')->where($parent_id)->select();
		$this->assign('region',$region);
		//先修改购物车数量
		$list=M("Buy_cart")->where(['member_id'=>$_SESSION['think']['USER_KEY_ID'],'status'=>1])->select();
		if(empty($list)){
			$this->error("请添加购物车，在结算商品");
		}
			
		foreach ($_POST as $k=>$v){
			M("Buy_cart")->where(['id'=>$k,'member_id'=>$_SESSION['think']['USER_KEY_ID'],'status'=>1])->setField("num",$v);
		}
		$msg=$this->cart_money();
		if($msg['status'] != 1){
			$this->error($msg['info']);exit();
		}
		if($msg['status'] == 1){
			$allmoney=$msg['info'];
		}	
		$where['member_id'] = $_SESSION['think']['USER_KEY_ID']; 
		$where['status'] = 1;
		$address = M('App_address')->where($where)->find();
		$sheng = M('Areas')->where("areaId='{$address['province_id']}'")->find();
		$address['province'] = $sheng['areaName'];

		$shi = M('Areas')->where("areaId='{$address['city_id']}'")->find();
		$address['city'] = $shi['areaName'];

		$qu = M('Areas')->where("areaId='{$address['area_id']}'")->find();
		$address['area'] = $qu['areaName'];
		$this->assign("address",$address);
		$this->assign("allmoney",$allmoney);
		return $this->fetch();
	}
	/**
	 * 计算个人购物车物品一共多少钱
	 */
	private function cart_money(){
		
		$field="wst_buy_cart.*,wst_goods.name,wst_goods.shengyu_num,wst_goods.money";
		$buy_cart=M("Buy_cart")->alias('a')->field($field)	
									->join("wst_goods b","a.goods_id=b.id and a.status = 1 and member_id = '".$_SESSION['think']['USER_KEY_ID']."'")
									->select();
		$allmoney="";
		foreach ($buy_cart as $k=>$v){
			if($v['shengyu_num']<$v['num']){
				$data['status']=-1;
				$data['info']=($v['name']."库存不足".$v['num']."只有".$v['shengyu_num']);
				return $data;
			}
			$allmoney +=($v['num']*$v['money']);
		}
	
		$data['status']=1;
		$data['info']=$allmoney;
		$data['bc']=$buy_cart;
		return $data;
	}
	
	/**
	*交易成功页面 
	*/
	public function success_complete(){
		
		return $this->fetch();
	}


	/**
	 * 订单列表查看订单'''''''''''
	 */
	public function goods_user_list(){
		$where['member_id']=$_SESSION['think']['USER_KEY_ID'];
		$Goods_user = M('Goods_user'); // 实例化User对象
		$list = $Goods_user->where($where)->order('add_time desc')->paginate(20,false,['query'=>input()]);
		$page = $list->render ();
		$list = $list->all();
		foreach ($list as $k => $v) {
			$goodname = M('Goods')->where(array('id'=>$list[$k]['goods_id']))->find();
			$list[$k]['gname'] = $goodname['name'];
		}
		$this->assign('list',$list);
		$this->assign('page',$page);
		return $this->fetch();
	}
 
}